package com.example.sicnuaccountingapp.ui.transaction

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.AdapterView.OnItemSelectedListener
import android.widget.ArrayAdapter
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import com.example.sicnuaccountingapp.R
import com.example.sicnuaccountingapp.data.entity.Category
import com.example.sicnuaccountingapp.data.entity.Transaction
import com.example.sicnuaccountingapp.data.entity.TransactionType
import com.example.sicnuaccountingapp.databinding.DialogAddTransactionBinding
import com.example.sicnuaccountingapp.utils.PreferencesManager
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.google.android.material.tabs.TabLayout
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import javax.inject.Inject

@AndroidEntryPoint
class EditTransactionDialog : BottomSheetDialogFragment() {
    private var _binding: DialogAddTransactionBinding? = null
    private val binding get() = _binding!!
    
    private val viewModel: AddTransactionViewModel by viewModels()
    private var selectedCategory: Category? = null
    private var transaction: Transaction? = null
    private var currentType: TransactionType = TransactionType.EXPENSE

    @Inject
    lateinit var preferencesManager: PreferencesManager

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = DialogAddTransactionBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setupViews()
        observeState()
        
        transaction?.let {
            // 设置初始值
            binding.amountEdit.setText(it.amount.toString())
            binding.noteEdit.setText(it.note)
            // 设置交易类型
            binding.typeTabLayout.selectTab(
                binding.typeTabLayout.getTabAt(
                    if (it.type == TransactionType.INCOME) 1 else 0
                )
            )
            viewModel.setType(it.type)
            currentType = it.type
        }
        
        viewModel.setUserId(preferencesManager.userId)
    }

    private fun setupViews() {
        setupTabLayout()
        setupCategoryDropdown()

        binding.saveButton.setOnClickListener {
            saveTransaction()
        }

        binding.deleteButton?.apply {
            visibility = if (transaction != null) View.VISIBLE else View.GONE
            setOnClickListener {
                showDeleteConfirmDialog()
            }
        }
    }

    private fun setupTabLayout() {
        binding.typeTabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
                currentType = when (tab?.position) {
                    1 -> TransactionType.INCOME
                    else -> TransactionType.EXPENSE
                }
                viewModel.setType(currentType)
            }
            override fun onTabUnselected(tab: TabLayout.Tab?) {}
            override fun onTabReselected(tab: TabLayout.Tab?) {}
        })
    }

    private fun setupCategoryDropdown() {
        viewLifecycleOwner.lifecycleScope.launch {
            viewModel.categories.collect { categories ->
                val adapter = ArrayAdapter(
                    requireContext(),
                    android.R.layout.simple_dropdown_item_1line,
                    categories.map { it.name }
                )
                binding.categoryAutoComplete.setAdapter(adapter)

                // 如果是编辑模式，设置初始分类
                transaction?.categoryId?.let { categoryId ->
                    val category = categories.find { it.categoryId == categoryId }
                    category?.let {
                        selectedCategory = it
                        binding.categoryAutoComplete.setSelection(categories.indexOf(category))
                    }
                }
            }
        }

        binding.categoryAutoComplete.onItemSelectedListener=object :OnItemSelectedListener{
            override fun onItemSelected(p0: AdapterView<*>?, p1: View?, position: Int, p3: Long) {
                val categories = viewModel.categories.value
                if (position in categories.indices) {
                    selectedCategory = categories[position]
                }
            }

            override fun onNothingSelected(p0: AdapterView<*>?) {

            }

        }
    }

    private fun observeState() {
        viewLifecycleOwner.lifecycleScope.launch {
            viewModel.state.collect { state ->
                when (state) {
                    is AddTransactionUiState.Success -> dismiss()
                    is AddTransactionUiState.Error -> {
                        Toast.makeText(context, state.message, Toast.LENGTH_SHORT).show()
                    }
                    else -> {}
                }
            }
        }
    }

    private fun saveTransaction() {
        val amountStr = binding.amountEdit.text.toString()
        val note = binding.noteEdit.text.toString()

        if (amountStr.isBlank()) {
            Toast.makeText(context, R.string.please_input_amount, Toast.LENGTH_SHORT).show()
            return
        }

        if (selectedCategory == null) {
            Toast.makeText(context, R.string.please_select_category, Toast.LENGTH_SHORT).show()
            return
        }

        val amount = amountStr.toDoubleOrNull()
        if (amount == null || amount <= 0) {
            Toast.makeText(context, R.string.please_input_valid_amount, Toast.LENGTH_SHORT).show()
            return
        }

        if (transaction != null) {
            viewModel.updateTransaction(
                transaction!!.copy(
                    amount = amount,
                    categoryId = selectedCategory?.categoryId,
                    categoryName = selectedCategory?.name,
                    note = note.takeIf { it.isNotBlank() },
                    type = currentType
                )
            )
        } else {
            viewModel.addTransaction(
                amount = amount,
                categoryId = selectedCategory?.categoryId,
                categoryName = selectedCategory?.name,
                note = note.takeIf { it.isNotBlank() }
            )
        }
    }

    private fun showDeleteConfirmDialog() {
        AlertDialog.Builder(requireContext())
            .setTitle(R.string.delete_transaction)
            .setMessage(R.string.delete_transaction_confirm)
            .setPositiveButton(R.string.confirm) { _, _ ->
                transaction?.let { viewModel.deleteTransaction(it) }
            }
            .setNegativeButton(R.string.cancel, null)
            .show()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    companion object {
        const val TAG = "EditTransactionDialog"

        fun newInstance(transaction: Transaction? = null): EditTransactionDialog {
            return EditTransactionDialog().apply {
                this.transaction = transaction
            }
        }
    }
} 